﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LigerMVC.IDataAccess;
using System.Data.Entity;
using System.Data;
using System.Linq.Expressions;
using LigerMVC.Common.Extensions;
using LigerMVC.Common;

namespace LigerMVC.DataAccess
{
    public abstract class DataAccessBase<T> : IDataAccess<T>
        where T: class
    {

        public DataAccessBase()
        {
          
        }
      

        public bool Update(T entity)
        {
            using (var db = new Entities())
            {
                db.Entry<T>(entity).State = System.Data.EntityState.Modified;
                var result = db.SaveChanges() > 0;
                return result;
            } 
        }

        public bool Insert(T entity)
        {
            using (var db = new Entities())
            {
                db.Set<T>().Add(entity);
                return db.SaveChanges() > 0; 
            }  
        }

        public void Delete(T entity)
        {
            using (var db = new Entities())
            {
                db.Set<T>().Remove(entity);
                db.SaveChanges(); 
            }  
        }
           

        public bool Exist(System.Linq.Expressions.Expression<Func<T, bool>> exp)
        {
            using (var db = new Entities())
            {
                return db.Set<T>().Any(exp);
            } 
        } 

        public T Find(System.Linq.Expressions.Expression<Func<T, bool>> exp)
        {
            var db = new Entities();
            return db.Set<T>().FirstOrDefault(exp); 
        }


        public List<T> FindAll()
        {
            var db = new Entities();
            return db.Set<T>().ToList();
        }

        public List<T> GetList(Common.FilterGroup filter)
        {
            var db = new Entities();
            return db.Set<T>().Query(filter).ToList();
        }

        public List<T> GetList(System.Linq.Expressions.Expression<Func<T, bool>> exp)
        {
            var db = new Entities();
            return db.Set<T>().Where(exp).ToList(); 
        }

        public Common.PagedData<T> GetPaged(Common.QueryDescriptor descriptor)
        {
            var db = new Entities();
            var query = db.Set<T>().AsQueryable<T>();
            return query.AsNoTracking().Page(descriptor);

        }


        public IQueryable<T> Query()
        {
            var db = new Entities();
            return db.Set<T>().AsQueryable();
        }

        public IEnumerable<T> SqlQuery(string sql, params object[] parms)
        {
            var db = new Entities();
            return db.Database.SqlQuery<T>(sql, parms);

        }
    }
}
